<template>
  <CommonPage>
    <template #action>
      <NButton v-permission="'AddPlayer'" type="primary" @click="handleAdd()">
        <i class="i-material-symbols:add mr-4 text-18" />
        新增球员
      </NButton>
    </template>

    <MeCrud
      ref="$table"
      v-model:query-items="queryItems"
      :scroll-x="1200"
      :columns="columns"
      :get-data="api.read"
    >
      <MeQueryItem label="球员名" :label-width="50">
        <n-input
          v-model:value="queryItems.player_name"
          type="text"
          :allow-input="noSideSpace"
          placeholder="请输入球员名"
          clearable
        />
      </MeQueryItem>

      <MeQueryItem label="归属球队" :label-width="66">
        <n-select v-model:value="queryItems.value" clearable :options="teamList" />
      </MeQueryItem>
    </MeCrud>

    <MeModal ref="modalRef" width="520px">
      <n-form
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
        :disabled="modalAction === 'view'"
      >
        <n-form-item
          label="球员名字"
          path="player_name"
          :rule="{
            required: true,
            message: '请输入球员名字',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.player_name" :allow-input="noSideSpace" :disabled="modalAction !== 'add'" />
        </n-form-item>
        <!-- <n-form-item
          label="球衣号码"
          path="player_number"
          :rule="{
            required: true,
            message: '请输入球员球衣号码',
            trigger: ['input', 'change'],
          }"
        > -->
        <n-form-item
          label="球衣号码"
          path="player_number"
        >
          <n-input v-model:value="modalForm.player_number" type="text" :allow-input="onlyAllowNumber" />
        </n-form-item>
        <n-form-item
          label="身高(cm)"
          path="height"
          :rule="{
            required: true,
            message: '请输入球员身高',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.height" type="text" :allow-input="onlyAllowNumber" />
        </n-form-item>
        <n-form-item
          label="体重(kg)"
          path="weight"
          :rule="{
            required: true,
            message: '请输入球员体重',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.weight" :allow-input="onlyAllowNumber" />
        </n-form-item>
        <n-form-item v-if="['add', 'edit'].includes(modalAction)" label="位置" path="position">
          <n-select
            v-model:value="modalForm.position"
            :options="positionList"
            label-field="label"
            value-field="value"
            clearable
            filterable
          />
        </n-form-item>
        <n-form-item v-if="['add', 'edit'].includes(modalAction)" label="所属球队" path="team_id">
          <n-select
            v-model:value="modalForm.team_id"
            :options="teamList"
            label-field="label"
            value-field="value"
            clearable
            filterable
          />
        </n-form-item>
        <n-form-item v-if="['add', 'edit'].includes(modalAction)" label="所属赛季" path="session">
          <n-select
            v-model:value="modalForm.session"
            :options="_sessionList"
            label-field="label"
            value-field="value"
            clearable
            filterable
          />
        </n-form-item>
      </n-form>
    </MeModal>
  </CommonPage>
</template>

<script setup>
import { NAvatar, NButton, NSwitch, NTag } from 'naive-ui'
import api from './api'
import { formatDateTime } from '@/utils'
import { MeCrud, MeModal, MeQueryItem } from '@/components'
import { useCrud } from '@/composables'

defineOptions({ name: 'PlayerList' })
function onlyAllowNumber(value) {
  return !value || /^\d+$/.test(value)
};
function noSideSpace(value) {
  return !value.startsWith(' ') && !value.endsWith(' ')
}
const $table = ref(null)
/** QueryBar筛选参数（可选） */
const queryItems = ref({})

onMounted(() => {
  $table.value?.handleSearch()
})

const sessionList = [
  { label: '全部', value: '' },
  { label: '2025（第七届）', value: 7 },
  { label: '2024（第六届）', value: 6 },
]
const _sessionList = sessionList.filter(item => item.value !== '')
const positionList = [
  { label: '待定', value: '待定' },
  { label: '后卫', value: '后卫' },
  { label: '前锋', value: '前锋' },
  { label: '中锋', value: '中锋' },
]
const teamList = ref([])
// const roles = ref([])
api.getAllTeams().then(({ data = [] }) => (teamList.value = data.pageData.map(item => ({ label: item.team_name, value: item.id }))))
// api.getAllRoles().then(({ data = [] }) => (roles.value = data))

const {
  modalRef,
  modalFormRef,
  modalForm,
  modalAction,
  handleAdd,
  handleDelete,
  handleEdit,
} = useCrud({
  name: '球员',
  initForm: { enable: true, session: 7, position: '待定' },
  doCreate: api.create,
  // doDelete: api.delete,
  doUpdate: api.update,
  refresh: () => $table.value?.handleSearch(),
})

const columns = [
  {
    title: '头像',
    key: 'avatar',
    width: 80,
    render: ({ avatar }) =>
      h(NAvatar, {
        size: 'medium',
        src: avatar,
      }),
  },
  { title: '姓名', key: 'player_name', width: 80, ellipsis: { tooltip: true } },
  { title: '号码', key: 'player_number', width: 50 },
  { title: '归属球队', key: 'team_id', width: 80,
    //   , render(row) {
    //         console.log(teamList,Array.isArray(teamList._rawValue))
    //         const _item = teamList._rawValue.find(item => item.value === row.id);
    //         console.log("归属球队",row.id,_item)
    //       return _item ? _item.label : "待定";
    //     }
  },
  { title: '位置', key: 'position', width: 80, ellipsis: { tooltip: true } },
  {
    title: '身高cm/体重kg',
    key: 'weight',
    width: 120,
    render(row) {
      return h('span', `${row.height}cm / ${row.weight}kg`)
    },
  },
  { title: '场均得分', key: 'ave_score', width: 80, ellipsis: { tooltip: true } },
  { title: '场均犯规', key: 'ave_foul', width: 80, ellipsis: { tooltip: true } },
  { title: '总出场次', key: 'total_field', width: 80, ellipsis: { tooltip: true } },
  {
    title: '创建时间',
    key: 'createTime',
    width: 100,
    render(row) {
      return h('span', formatDateTime(row.createTime))
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => handleEdit(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-carbon:user-role text-14' }),
          },
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },
]
</script>
